# -*- coding: utf-8 -*-
"""
参数优化结果对话框
"""
from PySide6.QtWidgets import QVBoxLayout, QHBoxLayout
from PySide6.QtCore import Qt
from ui.components.base.base_dialog import TgBaseDialog
from ui.components.buttons.button import TgButton
from ui.components.layouts.vbox_layout import TgVBoxLayout
from ui.components.layouts.hbox_layout import TgHBoxLayout
from ui.components.composite.table import TgTable
from ui.components.dialogs.file_dialog import TgFileDialog
from ui.components.dialogs.message_box import TgMessageBox
import csv
import logging
logger = logging.getLogger(__name__)


class OptimizationResultDialog(TgBaseDialog):
    """参数优化结果对话框"""
    
    def __init__(self, result_values, target_display_name: str, parent=None):
        self.result_values = result_values or []
        self.target_display_name = target_display_name
        super().__init__(parent)
        self.setWindowTitle("参数优化结果")
        self.resize(1000, 500)
    
    def setup_ui(self):
        """设置UI"""
        main_layout = TgVBoxLayout(self)
        # 允许对话框自由调整大小，避免外部布局强制限制高度
        self.setSizeGripEnabled(True)
        
        # 创建结果表格
        self.result_table = TgTable(editable=False, font_size='small')
        # 启用竖向滚动条（始终显示）
        if hasattr(self.result_table, 'table_widget'):
            self.result_table.table_widget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
            self.result_table.table_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        
        # 设置表格数据
        self._setup_table_data()
        
        main_layout.addWidget(self.result_table)
        
        # 按钮区域
        button_layout = TgHBoxLayout()
        button_layout.addStretch()
        
        self.save_button = TgButton("保存到CSV", theme="secondary")
        self.close_button = TgButton("关闭", theme="primary")
        
        self.save_button.clicked.connect(self._save_to_csv)
        self.close_button.clicked.connect(self.accept)
        
        button_layout.addWidget(self.save_button)
        button_layout.addWidget(self.close_button)
        
        main_layout.addLayout(button_layout)
    
    def _setup_table_data(self):
        """设置表格数据"""
        if not self.result_values:
            headers = ["参数", self.target_display_name]
            data = []
            self.result_table.set_data(headers, data)
            return
        
        # 统一参数列：以第一个结果为基础，合并所有结果中的参数名，保证行列对齐
        first_result = self.result_values[0]
        first_param_combo, _, first_statistics = first_result

        headers = []

        # 参数列名（保持首次出现顺序，其余追加）
        param_names = list(first_param_combo.keys()) if first_param_combo else []
        for combo, _, _ in self.result_values:
            if isinstance(combo, dict):
                for k in combo.keys():
                    if k not in param_names:
                        param_names.append(k)

        # 添加参数列
        for param_name in param_names:
            headers.append(param_name)

        # 添加目标值列（标注优化目标）
        target_header_name = f"{self.target_display_name}(优化目标)"
        headers.append(target_header_name)

        # 统计列：从预设清单中挑选在任意结果中出现过的键，保证所有行都占位
        stat_keys = [
            "total_return", "annual_return", "max_ddpercent",
            "sharpe_ratio", "return_drawdown_ratio", "daily_net_pnl"
        ]
        stat_names = [
            "总收益率", "年化收益率", "最大回撤%",
            "夏普比率", "收益回撤比", "日均盈亏"
        ]

        selected_stat_pairs = []  # [(key, display_name), ...]
        for stat_key, stat_name in zip(stat_keys, stat_names):
            appeared = any(isinstance(s, dict) and (stat_key in s) for _, _, s in self.result_values)
            # 若与优化目标显示名相同，则不重复添加统计列
            if appeared and stat_name != self.target_display_name:
                headers.append(stat_name)
                selected_stat_pairs.append((stat_key, stat_name))
        
        # 构建数据行
        data = []
        for param_combo, target_value, statistics in self.result_values:
            row = []
            
            # 参数值
            for param_name in param_names:
                row.append(str(param_combo.get(param_name, "")))
            
            # 目标值
            row.append(f"{target_value:.4f}" if isinstance(target_value, (int, float)) else str(target_value))
            
            # 其他统计指标
            for stat_key, _ in selected_stat_pairs:
                value = statistics.get(stat_key, None) if isinstance(statistics, dict) else None
                if isinstance(value, (int, float)):
                    if stat_key in ["total_return", "annual_return", "max_ddpercent"]:
                        row.append(f"{value:.2f}%")
                    elif stat_key == "return_drawdown_ratio":
                        row.append(f"{value:.2f}")
                    elif stat_key == "sharpe_ratio":
                        row.append(f"{value:.4f}")
                    else:
                        row.append(f"{value:.2f}")
                else:
                    row.append("" if value is None else str(value))
            
            data.append(row)
        
        # 设置表格数据
        self.result_table.set_data(headers, data)
        
        # 设置数值列样式
        numeric_columns = set()
        for i, header in enumerate(headers):
            if any(x in header for x in ["收益率", "回撤", "夏普", "收益回撤比", "盈亏"]) or header.startswith(self.target_display_name):
                numeric_columns.add(i)
        
        self.result_table.set_numeric_columns(numeric_columns)
        
        # 启用排序（通过 TgTable 提供的接口）
        self.result_table.enable_sorting(True)
        
        # 默认按目标值列降序排序（使用内部 QTableWidget）
        target_column = headers.index(target_header_name)
        if hasattr(self.result_table, 'table_widget'):
            self.result_table.table_widget.sortByColumn(target_column, Qt.DescendingOrder)
    
    def _save_to_csv(self):
        """保存结果到CSV文件"""
        try:
            dialog = TgFileDialog(self)
            file_path = dialog.get_save_file_name(
                title="保存优化结果",
                extensions=["csv"],
                default_name=f"optimization_result_{self.target_display_name}.csv"
            )
            
            if not file_path:
                return
            
            # 获取底层 QTableWidget 以便导出
            table_widget = self.result_table.table_widget
            rows = table_widget.rowCount()
            cols = table_widget.columnCount()
            
            # 获取表头
            headers = []
            for col in range(cols):
                header_item = table_widget.horizontalHeaderItem(col)
                headers.append(header_item.text() if header_item else f"Column_{col}")
            
            # 写入CSV文件
            with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:
                writer = csv.writer(csvfile)
                
                # 写入表头
                writer.writerow(headers)
                
                # 写入数据行
                for row in range(rows):
                    row_data = []
                    for col in range(cols):
                        item = table_widget.item(row, col)
                        row_data.append(item.text() if item else "")
                    writer.writerow(row_data)
            
            TgMessageBox.information(self, "保存成功", f"优化结果已保存到:\n{file_path}")
            
        except Exception as e:
            logger.exception(e)
            TgMessageBox.warning(self, "保存失败", f"保存优化结果时发生错误:\n{e}")